package com.tinygone.eurekauserhystrix.controller;

import com.netflix.discovery.converters.Auto;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.tinygone.eurekauserhystrix.feign.IMovieFeignClient;
import com.tinygone.eurekauserhystrix.pojo.Movie;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @author liqigang
 */
@RestController
public class TestHystrixController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private IMovieFeignClient movieFeignClient;

    @Value("${user.movieUrl}")
    private String movieUrl;

    @GetMapping("/rest-hystrix-movie/{id}")
    @HystrixCommand(fallbackMethod = "movieByIdFallback",
            commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000"),
            @HystrixProperty(name = "execution.isolation.strategy", value="THREAD")
        })
    public Movie movieById(@PathVariable(name = "id") String id) {
        Thread currentThread = Thread.currentThread();
        System.err.println("1:当前线程的名称为："+ currentThread.getName());

        Movie mm = restTemplate.getForObject(movieUrl + "movie/" + id, Movie.class);

        return mm;
    }

    public Movie movieByIdFallback(String id) {
        Movie movie = new Movie();
        movie.setId("-1");
        movie.setName("movieByIdFallback");
        movie.setAuthor("unknow");
        return movie;
    }

    @GetMapping("/feign-hystrix-movie/{id}")
    @HystrixCommand(fallbackMethod = "movieByIdFallback")
    public Movie movieByIdFeign(@PathVariable(name = "id") String id) {
        return movieFeignClient.getMovieById(id);
    }
}
